package edu.inf3.j2ee.config;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ConfigFactory {
	
	public static final String CONFIGURATION_FILE = "configuration.xml";

	public static Config getConfigInstance (){
		Config c = new Config();
		FileInputStream fis;
		
		try {
			fis = new FileInputStream(ConfigFactory.CONFIGURATION_FILE);
			XMLDecoder xml = new XMLDecoder(new BufferedInputStream(fis));
			
			c.setMap(xml.readObject());
			xml.close();
			
		} catch (FileNotFoundException e) {
			setConfigDefault(c);
			try {
				ConfigFactory.saveConfig(c);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return c;
	}
	
	public static void setConfigDefault (Config c){
		if (c.count() == 0){
			c.addPropertie("MYSQL_HOSTNAME", "localhost");
			c.addPropertie("MYSQL_PORT", new Integer(3399));
			c.addPropertie("MYSQL_DB", "project");
			c.addPropertie("MYSQL_USERNAME", "root");
			c.addPropertie("MYSQL_PASSWORD", "");
		}
	}
	
	public static void saveConfig (Config c) throws Exception{
		FileOutputStream fos = new FileOutputStream(ConfigFactory.CONFIGURATION_FILE);
		XMLEncoder xml = new XMLEncoder(new BufferedOutputStream(fos));
		xml.writeObject(c.getMap());
		xml.close();
	}
	
}
